import tushare as ts
import emmongo.em_mongomanager as mongoManager
from LSTM.variableset import EMVar
import pymongo
from emutils import time_utils
import datetime
import pandas as pd

# 获取module list
# 获取code list
# 获取最后的形态统计
    # 判断拿数据库还是拿网络
    #

def detect_modules():
    return []

def detect_stks():
    return []

JD_SL_SHIZI_XING = '极度缩量十字星'
def detect_pattern(open, high, low, close):
    if (close - open)/open <0.001 and (close - open)/open >-0.001:
        return JD_SL_SHIZI_XING
    return 'DEFAULT'

def sta_pattern(stkcode):
    data = get_data(stkcode, ktype='60', pattern_handle=detect_pattern)
    data = data.head(10)
    # type = list(data['pattern'])[:10]
    count = data[data['pattern'] == JD_SL_SHIZI_XING].shape[0]
    if count!=0:
        return True
    else:
        return False

def get_data(stkcode, ktype, isindex=False, pattern_handle=detect_pattern, maxcount=100):
    need_get_from_ts , result = sta_time_range(stkcode, ktype, isindex)
    if need_get_from_ts:
        start_day = result[0].strftime(EMVar.FORMATE_YMD)
        end_day  = result[1].strftime(EMVar.FORMATE_YMD)
        df = ts.get_k_data(stkcode,start=start_day,end=end_day,autype='qfq',index=isindex,ktype=ktype)
        df = df.tail(maxcount)
        for index, row in df.iterrows():
            row['pattern'] = pattern_handle(row[EMVar.open], row[EMVar.high], row[EMVar.low], row[EMVar.close])
            row['ktype'] = ktype
            d = dict(row)
            mongoManager.db[mongoManager.COL_STK_MIN_HIS_DATA].update_one(
                {EMVar.date: d[EMVar.date], EMVar.code: d[EMVar.code]}, {'$set': d}, upsert=True)
        return df.iloc[::-1]
    else:
        # # 直接拿返回的数据
        df = pd.DataFrame(data=result)
        del df['_id']
        return df

def sta_time_range(stkcode,ktype, isindex, maxcount=10 , throld = 60):
    cursor = mongoManager.db[mongoManager.COL_STK_MIN_HIS_DATA].find({EMVar.code:stkcode, 'ktype':ktype}).sort(EMVar.date, pymongo.DESCENDING)
    if cursor and cursor.count():
        l = list(cursor)
        lastTime = l[0][EMVar.date]
        delta = time_utils.delta_date(datetime.datetime.now(), datetime.datetime.strptime(lastTime, EMVar.FORMATE_YMD_HM))
        delta_min = delta[EMVar.MIN]
        if delta_min >= throld:
        # if delta_min >= 1000:
            # 返回最近5天
            return True, (time_utils.get_next_offset_work_day(offset=-10),time_utils.get_next_offset_work_day())
        else:
            return (False, l)
    else:
        #返回最近5天
        return True, (time_utils.get_next_offset_work_day(offset=-10),time_utils.get_next_offset_work_day())


    pass


sta_pattern('002795')
